#!/usr/bin/env python
#coding:utf-8
import os,re,copy,socket
from flask import Flask,render_template,request
from bin import login_handler,init_server,setup_api_server,update_offsite
from public.UploadFile import UpFile
from public.ViewLog import ViewLog
from config import Settings


app = Flask(__name__)



#首页与登陆
@app.route('/')
def index():
	return render_template('login.html')
@app.route('/ops',methods=['POST','GET'])
def ops_index():
    try:
        username = request.form['username']
        res=login_handler.login(username,request.form['password'])
    except Exception,e:
        return render_template('login.html', login_message='非法跳转，请先登录')
    if res:
		return render_template('opsystem_index.html',username=username)
    return render_template('login.html',login_message='User or password error!')
#直接访问模块的route
@app.route('/templates/<statc_page>')
def up_www_index(statc_page):
    return render_template(statc_page)


#初始化服务器
@app.route('/init_server',methods=['POST'])
def init_server_index():
    serip = request.form['ServerIp']
    sername = request.form['ServerName']
    seruser = request.form['ServerUser']
    serpasswd = request.form['ServerPassword']
    r_stat, r_res, n_stat, n_res = init_server.init_server(serip, sername, seruser, serpasswd)
    if n_stat  and r_stat:
        return render_template('init_server.html', no_message='{}\n{}'.format(n_res, r_res))
    else:
        return render_template('init_server.html', ok1_message=n_res, ok2_message=r_res)


#添加api节点
@app.route('/add_api_server',methods=['POST'])
def add_api_server():
    serip=request.form['ServerIp']
    serhostname=request.form['ServerName']
    stat,result=setup_api_server.setup_api_server(serip,serhostname)
    if stat:
        return render_template('result_show.html', no_message="Install api_server's env Failed!-{}"
                               .format(result.replace('\n','<br/>')))
    else:
        return render_template('result_show.html', ok_message='The api_server env install Success!<br/><br/>%s'
                                                              %result.replace('\n','<br/>'))

@app.route('/undo_api_server',methods=['POST'])
def undo_api_server():
    try:
        serip=request.form['ServerIp']
    except Exception,e:
        return render_template('result_show.html',no_message=u'没有要取消的操作'+e)
    else:
        stat, result = setup_api_server.undo_api_server(serip)
        if stat:
            return render_template('result_show.html', no_message=result)
        else:
            return render_template('result_show.html', ok_message=u'操作已取消-{}'.format(result))

#更新网站
UpNewFiles=[]
@app.route('/upload_www',methods=['POST'])
def upload_www():
    do_upfile=UpFile()
    stat,result=do_upfile.upload_exec(request.files.getlist('newfiles'),Settings.set_www_updir)
    global UpNewFiles
    UpNewFiles=result
    if stat:
        return render_template('up_www.html', no_message=result)
    result = str(result).replace('u','')
    return render_template('up_www.html', ok1_message='{}--已上传'.format(result))

@app.route('/update_www',methods=['GET'])
def update_www():
    action=request.values.get('action')
    global UpNewFiles
    if len(UpNewFiles) == 1 and UpNewFiles[0].split('.')[-1] == 'zip':
        result=update_offsite.update_rollback_zip_exec(action).replace('\n','<br/>')
        if re.search('(?i)error|failed', result):
            return render_template('up_www.html',no_message=result)
        return render_template('up_www.html',ok1_message=result)
    if action == 'update':
        if UpNewFiles:
            res=update_offsite.update_rollback_exec(UpNewFiles,action).replace('\n','<br/>')
            NewUpFiles=copy.deepcopy(UpNewFiles)
            UpNewFiles=[]
            if re.search('(?i)error|failed',res):
                return render_template('up_www.html', no_message=res)
            return render_template('up_www.html',ok2_message='{}<br/>{}-已更新,已备份'.format(res,NewUpFiles))
        return render_template('up_www.html', no_message='没有要更新的上传文件,请先上传')
    elif action == 'rollback_file':
        # upload dir file list
        RollNewFiles=update_offsite.get_backfile_list()
        res = update_offsite.update_rollback_exec(RollNewFiles,action).replace('\n','<br/>')
        if re.search('(?i)error|failed',res):
            return render_template('up_www.html', no_message=res)
        return render_template('up_www.html',ok2_message='{}<br/>{}-已还原到更新前版本'.format(res,RollNewFiles))

    else:
        res=update_offsite.update_rollback_zip_exec(action).replace('\n','<br/>')
        if re.search('(?i)error|failed',res):
            return render_template('up_www.html', no_message=res)
        return render_template('up_www.html',ok1_message=res)


#查看日志
@app.route('/show_log/<hostname>',methods=['GET','POST'])
def server_show_log(hostname):
    from datetime import datetime
    ip = socket.gethostbyname(hostname)
    log_date = datetime.now().strftime('%Y%m%d')
    try:
        logtype = request.form['logtype']
    except Exception, e:
        return render_template('log_show.html', hostname=hostname, ip=ip, today=log_date)
    shownum = request.form['shownum']
    datetime = request.form['datetime']
    viewlog = ViewLog(hostname, logtype, datetime, shownum)
    res = viewlog.log_show().replace('\n', '<br/>')
    if re.search('(?i)error|failed', res):
        return render_template('result_show.html', no_message=res)
    return render_template('result_show.html', ok_message=res)